package qlsl.androiddesign.activity.subactivity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.pay.demo.PayDemoActivity;
import com.j256.ormlite.stmt.query.In;
import com.lidroid.xutils.HttpUtils;
import com.qlsl.androiddesign.kuaiwa.R;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
import qlsl.androiddesign.constant.Constant;
import qlsl.androiddesign.entity.commonentity.FragmentArgs;
import qlsl.androiddesign.entity.otherentity.OrderResult;
import qlsl.androiddesign.http.xutils.HttpProtocol;
import qlsl.androiddesign.library.citypicker.City2PopupWindow;
import qlsl.androiddesign.library.citypicker.City2PopupWindow.OnCitySelectListener;
import qlsl.androiddesign.listener.OnTextChangeListener;
import qlsl.androiddesign.method.UserMethod;
import qlsl.androiddesign.thread.HandlerThread;
import qlsl.androiddesign.util.commonutil.Log;
import qlsl.androiddesign.util.commonutil.NetUtils;
import qlsl.androiddesign.util.commonutil.SPUtils;
import qlsl.androiddesign.util.runfeng.AbJsonUtil;
import qlsl.androiddesign.util.runfeng.NetUtil;
import qlsl.androiddesign.util.runfeng.StringUtils;
import qlsl.androiddesign.util.runfeng.ToActivityUtil;
import qlsl.androiddesign.util.runfeng.UIUtils;

public class OrderActivity extends PayDemoActivity implements OnClickListener,
		OnCitySelectListener {

	EditText mRegisterEtPwd;
	EditText mRegisterEtRpPwd;
	TextView mOrderAddress;
	EditText mDetailAddress;

	protected OrderResult mOrderResult;
	protected HttpUtils httpUtils;
	protected String goodslist, maxcouldusepoint;// 订单信息
	protected double totalprice;// 商品总价格
	protected double discount;// 商品优惠价格
	public City2PopupWindow cityWindow;

	private final String KEY_USERNAME = "order_username";
	private final String KEY_PHONE = "order_phone";
	private final String KEY_PROVINCE = "order_province";
	private final String KEY_CITY = "order_city";
	private final String KEY_AREA = "order_area";
	private final String KEY_ADDRESS = "order_address";

	private String province;
	private String city;
	private String area;
	private String address;
	public int points;
	public int maxcould;
	private int num;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order);
		initView();
		initData();
		initListener();

	}

	protected void initListener() {

	}

	protected void initData() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			FragmentArgs args = (FragmentArgs) bundle
					.getSerializable("goumainBundle");
			goodslist = (String) args.get("goodslist");
			totalprice = (Double) args.get("totalprice");
			maxcouldusepoint = (String) args.get("maxcouldusepoint");
			discount = Integer.parseInt(maxcouldusepoint) * 0.1;

			// is_wb.setText("使用" + maxcouldusepoint + "挖币抵扣" + discount + "元");

			points = Integer.parseInt(UserMethod.getUser().getPoints());
			maxcould = Integer.parseInt(maxcouldusepoint);
			num = maxcould > points ? points : maxcould;// 计算使用最大挖币数
			my_wb.setText(totalprice + "元");
			use_wb.setText(num + "");

			my_money.setText("" + totalprice);

			// int num = (Integer) (Integer.parseInt(maxcouldusepoint) > Integer
			// .parseInt(UserMethod.getUser().getPoints()) ? Integer
			// .parseInt(UserMethod.getUser().getPoints())
			// : maxcouldusepoint);
			// int num = 10;

			// use_wb.setText("" + num);
			// money.setText("抵扣" + num / 10 + "元");

			// if (discount >= 50) {
			// is_wb.setText("使用" + 500 + "挖币抵扣" + 50 + "元");
			// } else {
			//
			// }

		}
	}

	TextView tv_title, my_money, my_wb;
	EditText use_wb;
	View btn_back;
	ToggleButton toggle;

	protected void initView() {
		findViewById(R.id.btn_right).setVisibility(View.GONE);
		mRegisterEtPwd = (EditText) findViewById(R.id.register_et_pwd);
		use_wb = (EditText) findViewById(R.id.use_wb);
		mRegisterEtRpPwd = (EditText) findViewById(R.id.register_et_rp_pwd);
		mOrderAddress = (TextView) findViewById(R.id.order_address);
		mDetailAddress = (EditText) findViewById(R.id.detail_address);
		tv_title = (TextView) findViewById(R.id.tv_title);
		my_money = (TextView) findViewById(R.id.my_money);
		my_wb = (TextView) findViewById(R.id.my_wb);
		toggle = (ToggleButton) findViewById(R.id.toggle);

		btn_back = findViewById(R.id.btn_back);
		tv_title.setText("收货人信息");
		cityWindow = new City2PopupWindow(this, this);
		use_wb.addTextChangedListener(textChangeListener);

		String username = (String) SPUtils.get(this, KEY_USERNAME, UserMethod
				.getUser().getUsername());
		String phone = (String) SPUtils.get(this, KEY_PHONE, UserMethod
				.getUser().getMobile());
		province = (String) SPUtils.get(this, KEY_PROVINCE, Constant.province);
		city = (String) SPUtils.get(this, KEY_CITY, Constant.city + "市");

		area = (String) SPUtils.get(this, KEY_AREA, Constant.area);
		address = (String) SPUtils.get(this, KEY_ADDRESS, "请输入详细地址");
		mRegisterEtPwd.setText(username);
		mRegisterEtRpPwd.setText(phone);
		mOrderAddress.setText(province + city + area);
		mDetailAddress.setText(address);

		// mOrderAddress.setText((String) SPUtils.get(this, "address",
		// UserMethod
		// .getUser().getProvincename()
		// + UserMethod.getUser().getCityname()
		// + UserMethod.getUser().getAreaname()));
		//
		//
		// mDetailAddress.setText((String) SPUtils.get(this, "addressdetail",
		// ""));

		btn_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private OnTextChangeListener textChangeListener = new OnTextChangeListener() {
		public void afterTextChanged(android.text.Editable s) {
			if (TextUtils.isEmpty(s.toString())) {
				my_money.setText("" + totalprice);// +
			} else {
				int num = Integer.parseInt(s.toString());
				if (points > num && maxcould >= num)
					my_money.setText("" + (totalprice - num / 10));
				else {
					my_money.setText("" + totalprice);// +
					showToast("请查看挖币使用规则");
				}
			}

		};
	};

	/**
	 * 隐藏输入法<br/>
	 */
	public void hideSoftInput() {
		InputMethodManager imm = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (this.getCurrentFocus() != null) {
			imm.hideSoftInputFromWindow(
					this.getCurrentFocus().getWindowToken(), 0);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.order_address_layout:
			hideSoftInput();

			cityWindow.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);

			// Intent intent0 = new Intent(this, SelectCityActivity.class);
			// startActivityForResult(intent0,
			// Constant.SELECT_CITY_RESULT_CODE);
			break;
		case R.id.register_next:
			if (check()) {
				requestData(v);
			}
			break;
		case R.id.wb_guize:// 挖币使用规则
			FragmentArgs args = new FragmentArgs();
			args.add("name", "挖币使用规则");
			args.add("url", "file:///android_asset/other/use_role.html");
			ToActivityUtil.toNextActivity(this, RefundActivity.class, "data",
					args);
			break;
		case R.id.toggle:// 点击计算价格
			if (toggle.isChecked()) {
				my_money.setText("" + (totalprice - num / 10));
			} else {
				my_money.setText("" + totalprice);
			}
			break;
		}
	};

	public void requestData(final View v) {
		v.setEnabled(false);
		cacheUserManager();
		new HandlerThread("ww", "subOrder") {
			public void run() {
				HttpProtocol protocol = new HttpProtocol();

				protocol = protocol.setMethod("submitorder")
						.addParam("goodslist", goodslist)
						.addParam("totalprice", totalprice + "")
						.addParam("consigneeaddress", getDeatilAddress())
						.addParam("consigneearea", getConsigneearea())
						.addParam("consigneecity", consigneecity())

						.addParam("consigneeprovince", consigneeprovince())
						.addParam("consigneemobile", phoneNumber())
						.addParam("consigneename", getUserName());

				protocol.addParam("usedpoint", getUsedPoint());

				JSONObject jo = protocol.post();
				mOrderResult = (OrderResult) AbJsonUtil.fromJson(
						jo.toJSONString(), OrderResult.class);
				if (mOrderResult.OK()
						&& NetUtils.isConnected(getApplicationContext())) {
					UIUtils.runOnUIThread(new Runnable() {
						@Override
						public void run() {
							v.setEnabled(true);
							if (NetUtils.isConnected(getApplicationContext())) {
								showToast("请稍后...");
								pay(null);
							}
						}
					});
				} else {
					showAsynToast("提交订单失败，请重新提交");
				}
			}

		}.start();
	}

	public void cacheUserManager() {
		address = mDetailAddress.getText().toString().trim();
		SPUtils.put(this, KEY_USERNAME, mRegisterEtPwd.getText().toString()
				.trim());
		SPUtils.put(this, KEY_PHONE, mRegisterEtRpPwd.getText().toString()
				.trim());
		SPUtils.put(this, KEY_PROVINCE, province);
		SPUtils.put(this, KEY_CITY, city);
		SPUtils.put(this, KEY_AREA, area);
		SPUtils.put(this, KEY_ADDRESS, address);
	}

	public boolean check() {
		if (TextUtils.isEmpty(mRegisterEtPwd.getText().toString().trim())) {
			showToast("" + getString(R.string.people_names_null));
			return false;
		}
		if (!isMobileNo(mRegisterEtRpPwd.getText().toString().trim())) {
			showToast("" + getString(R.string.error_invalid_email));
			return false;
		}
		if (TextUtils.isEmpty(mOrderAddress.getText().toString().trim())) {
			showToast("" + getString(R.string.people_names_null));
			return false;
		}
		if (TextUtils.isEmpty(mDetailAddress.getText().toString().trim())) {
			showToast("" + getString(R.string.people_names_null));
			return false;
		}
		if (!NetUtil.isConnected(getApplicationContext())) {
			showToast("" + getString(R.string.not_network));
			return false;
		}
		return true;
	}

	public boolean isMobileNo(String email) {
		return StringUtils.isMobileNo(email);
	}

	// 详细地址
	protected String getDeatilAddress() {
		return address;
	}

	// 区
	protected String getConsigneearea() {
		return area;
	} // 市

	protected String consigneecity() {
		return city;
	}

	// 省
	protected String consigneeprovince() {
		return province;
	}

	// 联系电话
	protected String phoneNumber() {
		return "" + mRegisterEtRpPwd.getText().toString().trim();
	}

	// 用户名称
	protected String getUserName() {
		return "" + mRegisterEtPwd.getText().toString().trim();
	}

	// 获取用户输入的挖币
	private String getUsedPoint() {
		if (toggle.isChecked()) {
			return use_wb.getText().toString();
		}
		return "0";
	}

	/***
	 * 商品名称
	 **/
	protected String getShoppingName() {
		return "" + totalprice;
	}

	/***
	 * 商品价格
	 **/
	protected String getShoppingPrice() {
		// return "" + (totalprice - discount);
		return my_money.getText().toString();
	}

	protected String getNotifyUrld() {
		return "http://kw.runfkj.com/appservice/notifyurl.action";
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 */
	protected String getOutTradeNo() {
		String key;
		if (mOrderResult != null) {
			// showToast("服务器产生的订单号码:" + mOrderResult.getOuttradno());
			return mOrderResult.getOuttradno();
		} else {
			SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
					Locale.getDefault());
			Date date = new Date();
			key = format.format(date);

			Random r = new Random();
			key = key + r.nextInt();
			key = key.substring(0, 15);
		}
		return key;
	}

	@Override
	public void onCitySelect(String city) {
		province = cityWindow.getCityPicker().getProvince();
		this.city = cityWindow.getCityPicker().getCity();
		area = cityWindow.getCityPicker().getCouny();

		mOrderAddress.setText(province + this.city + area);
	}
}
